#!/bin/bash

# Copyright (c) 2011-2014 Apple Inc. All Rights Reserved.

# IMPORTANT NOTE: This file is licensed only for use on Apple-branded
# computers and is subject to the terms and conditions of the Apple Software
# License Agreement accompanying the package this file is a part of.
# You may not port this file to another platform without Apple's written consent.

>&2 echo "(c) 2014 Apple Inc.  All rights reserved."

bundle_installer_requirements='(anchor apple generic and
                                certificate 1[subject.CN] = "Apple Software Update Certification Authority") or
                               (anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.10] exists) or
                               (anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists and
                                (certificate leaf[field.1.2.840.113635.100.6.1.14] or
                                 certificate leaf[field.1.2.840.113635.100.6.1.13]))'

app_requirements='(anchor apple) or
                  (anchor apple generic and certificate leaf[field.1.2.840.113635.100.6.1.9] exists) or
                  (anchor apple generic and certificate 1[field.1.2.840.113635.100.6.2.6] exists
                   and certificate leaf[field.1.2.840.113635.100.6.1.13] exists)'

codesign=/usr/bin/codesign

build_version=$(sw_vers -buildVersion)
v1=$(sed 's/^\([0-9]*\).*/\1/' <<< $build_version)
v2=$(sed 's/^[0-9]*\([A-Z]\).*/\1/' <<< $build_version)

if [[ "$v1" -lt 13 || ( "$v1" -eq 13 && "$v2" < "F" ) ]]; then
    >&2 echo "This tool requires OS X Version 10.9.5 or higher."
    exit 3
fi

ok=1
for target; do
    use_codesign=1

    if [[ $target == *.pkg || $target == *.mpkg ]]; then
        if [[ -d $target ]]; then
            >&2 echo "${target}: Warning: bundle installers are deprecated, please use regular installer packages."
            requirements=$bundle_installer_requirements
        else
            use_codesign=0

            pkgutil_output=$(pkgutil --check-signature "$target" 2>&1)
            result=$?

            [ $result -ne 0 ] && >&2 echo $pkgutil_output
        fi
    else
        requirements=$app_requirements
    fi

    if [[ $use_codesign -eq 1 ]]; then
        $codesign -v --deep -R="${requirements}" "$target"
        result=$?

        if [[ $result -eq 3 ]]; then
            >&2 echo "${target}: The target is not signed with Developer ID or by the Mac App Store."
        fi
    fi

    [ $# -ne 1 ] && echo -n "${target}: "
    if [[ $result -eq 0 ]]; then
        echo YES
    else
        echo NO
        ok=0
    fi
done

[ $ok -eq 1 ] && exit 0 || exit 2
